<template>
  <div>
    <crumbs @goBack="() => {}" :superiorMenu="['库存管理']" currentMenu="库存盘点" style="margin-bottom: 12px" />
    <a-card :bordered="false" style="height: calc(100vh - 215px)">
      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button @click="handleShowFilter" icon="filter" style="margin-right: 10px">
          筛选 <span style="color: #1890ff; margin-left: 5px">{{ searchNum }}</span></a-button
        >
        <a-button @click="showColumn" icon="unordered-list" style="margin-right: 10px"> 设置列 </a-button>
        <div class="right-btn">
          <a-button @click="handleAdd" type="primary" class="btns"> +新建 </a-button>
        </div>
        <!-- <a-button @click="handleDetail" type="primary" style="float: right" icon="plus">进详情</a-button> -->
      </div>
      <!-- 设置列 -->
      <SetColumn
        columnName="设置列"
        ref="SetColumn"
        v-if="showSetColumn"
        @sureBtn="sureBtn"
        @cancelBtn="showSetColumn = false"
      />
      <!-- table区域-begin -->
      <div>
        <a-table
          :key="tableKey"
          ref="table"
          size="middle"
          rowKey="goodsId"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="false"
          :loading="loading"
          class="j-table-force-nowrap"
          @change="handleTableChange"
          :scroll="{ x: computedX, y: 'calc(100vh - 338px)' }"
          :components="drag(columns, 'STOCK_CHECK_LIST')"
        >
          <span slot="inventoryCode" :text="text" slot-scope="text, record">
            <a @click="handleDetail(record)">{{ text }}</a>
          </span>
          <span slot="actions" slot-scope="text, record">
            <a v-if="record.inventoryStatus == 'running'" @click="handleEdit(record)">继续盘点</a>
            <a v-if="record.inventoryStatus != 'running'" @click="handleDetail(record)">详情</a>
            <a v-if="record.inventoryStatus != 'running'" @click="exportAction(record)" style="margin-left: 20px"
              >导出</a
            >
            <a
              v-if="record.flowStatus == 'RUNNING' && record.createBy == currentUserId"
              style="margin-left: 20px"
              @click="handleWithdraw(record)"
              >撤回</a
            >
          </span>
          <!-- title搜索条件开始 -->
          <!-- 输入框搜索 -->
          <div
            v-for="(item, i) in filterDropdownList"
            :key="i"
            style="display: flex; padding: 8px"
          >
            <template :slot="item.scopedSlots.filterDropdown" slot-scope="{ column }">
              <a-input
                v-if="item.scopedSlots.filterDropdown === 'searchDropdown'"
                :placeholder="'请输入'[column.title]"
                v-model="queryParam[column.searchIndex]"
                style="width: 188px"
              />
              <a-select
                :mode="column.multi ? 'multiple' : 'default'"
                v-if="item.scopedSlots.filterDropdown === 'selectDropdown'"
                :placeholder="'请选择'[column.title]"
                allowClear
                style="width: 188px"
                v-model="queryParam[`${column.searchIndex}all`]"
                @change="(a) => changeSelect(a, column.searchIndex)"
                :labelInValue="true"
              >
                <a-select-option v-for="(items, i) in column.options" :key="i" :value="items.key">{{
                  items.label
                }}</a-select-option>
              </a-select>
              <a-button
                v-if="item.scopedSlots.filterDropdown !== 'tooltip'"
                type="primary"
                style="width: 80px; margin-left: 20px"
                @click="searchQuery"
              >
                搜索
              </a-button>
            </template>
          </div>
          <a-icon slot="searchIcon" type="search" />

          <!-- title搜索条件结束 -->
        </a-table>
      </div>
      <!-- table区域-end -->
      <!-- 底部分页 -->
      <div
        :style="{
          position: 'fixed',
          bottom: 0,
          right: 0,
          zIndex: 2,
          width: '100%',
          background: '#fff',
          padding: '24px',
        }"
      >
        <div style="display: inline-block; float: right">
          <a-pagination
            :total="ipagination.total"
            v-model="ipagination.current"
            :page-size-options="ipagination.pageSizeOptions"
            :page-size="ipagination.pageSize"
            @change="onChangePage"
            @showSizeChange="onChangePage"
            show-quick-jumper
            show-size-changer
          />
        </div>
      </div>
      <!-- 表格条数 -->
      <div class="tableSelect">
        <span style="margin: 0 20px">{{ `共${this.dataSource.length} 项` }}</span>
      </div>
      <!-- 侧边筛选 -->
      <a-drawer
        width="500"
        height="100vh"
        :bodyStyle="{ background: '#f5f5f5', padding: '0' }"
        :closable="true"
        :visible="showFilter"
        @close="showFilter = false"
      >
        <formSearch ref="dataSearch" @searchDate="searchDate" />
      </a-drawer>
    </a-card>
    <windowForm ref="windowForm" @refresh="searchQuery"></windowForm>
    <windowDetail ref="windowDetail"></windowDetail>
  </div>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { tableMixinReport } from '@/mixins/tableMixinReport'
import { columns, allColumn, getTypeList } from './column.js'
import tableDragResize from '@/mixins/tableDragResize'
import { API } from '@/api/requestFzs'
import { getEnableOne } from '@/api/api'
import { downFilePost } from '@/api/manage'
const actionArr = [
  {
    fixed: 'right',
    title: '操作',
    align: 'left',
    dataIndex: 'actions',
    width: 150,
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
  mixins: [tableMixinReport, tableDragResize],
  components: {
    windowForm: (resolve) => require(['@/views/warehouseManagement/stockCheck/stockCheckForm'], resolve),
    windowDetail: (resolve) => require(['@/views/warehouseManagement/stockCheck/stockCheckDetail'], resolve),
  },
  data() {
    return {
      // 表头
      columns: columns.map((e) => {
        e.align = 'left'
        return e
      }),
      actionArr,
      allColumn: allColumn.map((e) => {
        e.align = 'left'
        return e
      }),
      url: {
        list: '/wms/wmsWarehouseInventory/list',
      },
      tableData: {},
      EntityName: this.BUSI_CONST.Entity.STOCK_CHECK_LIST, //用于表头设计,值保证是唯一的即可
      currentUserId: '',
      tableKey: 1.9,
    }
  },
  computed: {},
  created() {
    getEnableOne({ id: 'WMS_WAREHOUSE_INVENTORY', type: 'add' }).then((res) => {
      if (res.result && res.result == 'false') {
        this.allColumn = this.allColumn.filter((item) => item.title != '审批状态')
        this.columns = this.columns.filter((item) => item.title != '审批状态')
      }
    })
    let currentLogin = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value
    this.currentUserId = currentLogin.id
    getTypeList()
  },
  methods: {
    handleAdd() {
      this.$refs.windowForm.initForm()
    },
    handleEdit(v) {
      this.$refs.windowForm.initForm(v.id)
    },
    handleDetail(v) {
      this.$refs.windowDetail.initDetail(v.id)
    },
    exportAction(record) {
      let fileName = `库存盘点 ${record.inventoryCode}`
      let postData = {
        id: record.id,
      }
      downFilePost('/wms/wmsWarehouseInventory/exportInventoryDetails', postData).then((data) => {
        if (data.type == 'application/json') {
          const reader = new FileReader() //创建一个FileReader实例
          reader.readAsText(data, 'utf-8') //读取文件,结果用字符串形式表示
          reader.onload = function () {
            //读取完成后,**获取reader.result**
            const msg = JSON.parse(reader.result)
            this.$antdMessage.error(msg.message) //弹出错误提示
          }
          return
        }
        if (!data) {
          this.$antdMessage.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    /* 撤回 */
    handleWithdraw(v) {
      let that = this
      that.$antdConfirm({
        title: '确定撤回吗？',
        content: '撤回后暂不支持再次发起',
        onOk() {
          API.operateRevoke({ flowInstId: v.flowInstId }).then((res) => {
            if (res.code == 200) {
              that.$antdMessage.success(res.message)
              that.loadData(1)
            } else {
              that.$antdMessage.error(res.message)
            }
          })
        },
        onCancel() {},
      })
    },
  },
}
</script>
<style scoped lang="less">
.right-btn {
  float: right;
  display: flex;
  justify-content: flex-end;
  button {
    margin: 0 !important;
  }
}
/deep/.ant-card-body {
  padding: 20px 16px;
}
@import '~@/assets/less/public.less';
@import '~@assets/less/common.less';
</style>
